package com.hna.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HiveTempUtils {
	public HiveTempUtils() {

	}

	public HiveTempUtils(String Url, String UserName, String Passwd) {
		this.Url = Url;
		this.UserName = UserName;
		this.Passwd = Passwd;

	}

	public HiveTempUtils(String Url) {
		this.Url = Url;
	}

	private String Url;
	private String UserName = "";
	private String Passwd = "";
	private static String driverName = "org.apache.hive.jdbc.HiveDriver";
	private static Connection con = null;
	private Statement stmt;
	private ResultSet res;
	/** 日志 */
	static final Logger logger = LoggerFactory.getLogger(HiveTempUtils.class);

	public Boolean IsConClosed() {
		if (con == null) {
			return true;
		}
		try {
			return con.isClosed();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public Boolean Conn() throws SQLException {
		if (Url == null || Url == "") {
			logger.error("Connect Url is null");
			return false;
		}

		try {
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.exit(1);
		}

		String JdbcUrl = String.format("jdbc:hive2://%s", Url);

		con = DriverManager.getConnection(JdbcUrl, UserName, Passwd);
		stmt = con.createStatement();
		return true;
	}

	public ResultSet Runqry(String SqlStr) throws SQLException {

		res = stmt.executeQuery(SqlStr);
		return res;
	}

	public void RunCtx(String SqlStr) throws SQLException {

		stmt.execute(SqlStr);

	}
	
	public String GeString(String ColName) throws SQLException {
		return res.getString(ColName);
	}

	public long GeLong(String ColName) throws SQLException {
		return res.getLong(ColName);
	}

	public void closeStm() throws SQLException {
		if (stmt != null && !stmt.isClosed()) {
			stmt.close();
		}

		if (res != null && !res.isClosed()) {
			res.close();
		}
	}

	public Boolean DisCon() {
		try {
			if (!stmt.isClosed()) {
				stmt.close();
			}
			if (!con.isClosed()) {
				con.close();
			}
			if (!res.isClosed()) {
				res.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return true;
	}
}
